package com.grade.controller;

import com.grade.domain.LoginUser;
import com.grade.domain.Response;
import com.grade.domain.UserDto;
import com.grade.service.LoginService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

@RestController
@CrossOrigin(origins = "*") // 允许跨域请求，便于前端访问后端接口
public class LoginController {

    @Resource
    private LoginService loginService;

    /**
     * 登录接口：处理用户登录请求
     * @param loginUser 用户登录信息
     * @param session 当前会话对象
     * @return 返回登录结果（成功或失败）
     */
    @PostMapping("/login")
    public Response<UserDto> login(@RequestBody LoginUser loginUser, HttpSession session) {
        return loginService.login(loginUser, session);
    }

    /**
     * 获取验证码图片接口
     * @param response 用于返回验证码图片
     * @param session 当前会话对象
     * @return 返回验证码图片的字节数据
     */
    @GetMapping("/captcha")
    public ResponseEntity<byte[]> getCaptcha(HttpServletResponse response, HttpSession session) throws IOException {
        // 调用服务生成验证码并存储
        loginService.generateCaptcha(session);

        // 获取验证码图片
        BufferedImage captchaImage = (BufferedImage) session.getAttribute("captchaImage");

        if (captchaImage != null) {
            // 将图片转化为字节数组并返回
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(captchaImage, "jpg", baos);

            return ResponseEntity.ok()
                    .contentType(MediaType.IMAGE_JPEG)
                    .body(baos.toByteArray());
        } else {
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }

    /**
     * 获取验证码文本接口
     * @param session 当前会话对象
     * @return 返回验证码的文本
     */
    @GetMapping("/captcha-text")
    public String getCaptchaText(HttpSession session) {
        return (String) session.getAttribute("captcha");
    }
}
